package com.bhs.sansonglogistics.ui.order;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.maps.MapView;
import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.Location;
import com.bhs.sansonglogistics.bean.LogisticsTrackBean;
import com.bhs.sansonglogistics.bean.LogisticsTrackData;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.PictureShowBean;
import com.bhs.sansonglogistics.bean.SourceGoodsDetailsBean;
import com.bhs.sansonglogistics.bean.event.Event;
import com.bhs.sansonglogistics.bean.event.RefreshOrder;
import com.bhs.sansonglogistics.dialog.AttachMoreDialog;
import com.bhs.sansonglogistics.dialog.CustomBubbleAttachPopup;
import com.bhs.sansonglogistics.dialog.LogisticsTrackDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.LogisticsTrackAdapter;
import com.bhs.sansonglogistics.ui.adapter.PictureShowAdapter;
import com.bhs.sansonglogistics.ui.home.OrderGoodsListFragment;
import com.bhs.sansonglogistics.ui.mine.CustomerServiceActivity;
import com.bhs.sansonglogistics.ui.waybill.WaybillDetailsActivity;
import com.bhs.sansonglogistics.utils.CountDownTimerUtils;
import com.bhs.sansonglogistics.utils.DateUtils;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.StatusBarUtil;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.BubblePopupWindow;
import com.bhs.sansonglogistics.view.IInterceptChecker;
import com.bhs.sansonglogistics.view.SlideContentLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.util.SmartGlideImageLoader;
import com.lxj.xpopup.util.XPopupUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 订单详情
 */
public class OrderDetailsActivity extends BaseActivity implements IInterceptChecker, View.OnClickListener, NetCallBack {

    private MapView mMapView = null;
    private SlideContentLayout mSlideLayout;
    private ScrollView mSvInfo;
    private TextView mTvMore;

    private OrderDetailsReuse orderDetailsReuse;
    private SourceGoodsDetailsBean.DataDTO data;

    private Button btn_confirm_receipt;
    private Button mBtnConfirmReceipt;
    private Button mBtnConfirmDeparture;
    private Button mBtnConfirmSignFor;
    private Button mBtnReceiptPending;
    private LinearLayout mLlLogisticsTrack;
    private RelativeLayout mRlTitle;
    private View mView2;
    private LinearLayout mLlStowage;
    private TextView mTvLicensePlateNumber;
    private TextView mTvDriver;
    private TextView mTvDriverPhone;
    private TextView mTvArrivalInformation;
    private TextView mTvDepartureTime;
    private LinearLayout mLlSigner;
    private RecyclerView mRvSigner;
    private TextView mTvSignerTime;
    private RecyclerView mRvReceipt;
    private TextView mTvReceiptTime;
    private LinearLayout mLlReceipt;
    private Button mBtnIncrementalExpenses;
    private Button btnCashRegister;
    private TextView mTvHint;
    private RelativeLayout mRlOperation;
    private MapNavigation mapNavigation;//地图相关
    private Button mBtnWaybill;
    private Button btnConfirmCancellation;
    private String deliver_sn;
    private int module;//3上游来货
    private FrameLayout mFlTitle;


    @Override
    public int initLayout() {
        return R.layout.activity_order_details;
    }

    @SuppressLint("WrongViewCast")
    @Override
    public void initView() {
        JPushInterface.setBadgeNumber(this, 0);//清除角标
        module = getIntent().getIntExtra("module", 0);

        deliver_sn = getIntent().getStringExtra("deliver_sn");
        orderDetailsReuse = new OrderDetailsReuse(mActivity);
        btnConfirmCancellation = findViewById(R.id.btn_confirm_cancellation);
        btnConfirmCancellation.setOnClickListener(this);
        mBtnConfirmReceipt = findViewById(R.id.btn_confirm_receipt);
        mBtnConfirmDeparture = findViewById(R.id.btn_confirm_departure);
        mBtnConfirmSignFor = findViewById(R.id.btn_confirm_sign_for);
        mBtnReceiptPending = findViewById(R.id.btn_receipt_pending);
        mBtnConfirmReceipt.setOnClickListener(this);
        mBtnConfirmDeparture.setOnClickListener(this);
        mBtnConfirmSignFor.setOnClickListener(this);
        mBtnReceiptPending.setOnClickListener(this);
        mLlLogisticsTrack = findViewById(R.id.ll_Logistics_track);
        mRlTitle = findViewById(R.id.rl_title);
        mView2 = findViewById(R.id.view2);
        mLlLogisticsTrack.setOnClickListener(this);
        mLlStowage = findViewById(R.id.ll_stowage);
        mTvLicensePlateNumber = findViewById(R.id.tv_license_plate_number);
        mTvDriver = findViewById(R.id.tv_driver);
        mTvDriverPhone = findViewById(R.id.tv_driver_phone);
        mTvArrivalInformation = findViewById(R.id.tv_arrival_information);
        mTvDepartureTime = findViewById(R.id.tv_departure_time);
        mLlSigner = findViewById(R.id.ll_signer);
        mRvSigner = findViewById(R.id.rv_signer);
        mTvSignerTime = findViewById(R.id.tv_signer_time);
        mRvReceipt = findViewById(R.id.rv_receipt);
        mTvReceiptTime = findViewById(R.id.tv_receipt_time);
        mLlReceipt = findViewById(R.id.ll_receipt);
        mBtnIncrementalExpenses = findViewById(R.id.btn_incremental_expenses);
        mBtnIncrementalExpenses.setOnClickListener(this);
        btnCashRegister = findViewById(R.id.btn_cash_register);
        btnCashRegister.setOnClickListener(this);
        mTvHint = findViewById(R.id.tv_hint);
        mRlOperation = findViewById(R.id.rl_operation);
        mBtnWaybill = findViewById(R.id.btn_waybill);
        mBtnWaybill.setOnClickListener(this);
        findViewById(R.id.tv_service).setOnClickListener(this);

        mFlTitle = findViewById(R.id.fl_title);
        mFlTitle.post(new Runnable() {
            @Override
            public void run() {
                int viewHeight = mFlTitle.getHeight();
                int Height = mView2.getHeight();
                int layoutHeight = MyUtils.getScreenHeight(mContext) / 2 - viewHeight - Height;
                // mSlideLayout.setY(layoutHeight);
                mSlideLayout.setHeight(layoutHeight - 20);
                mMapView.setLayoutParams(new RelativeLayout.LayoutParams(MyUtils.getScreenWidth(mContext), MyUtils.getScreenHeight(mContext) / 2));
            }
        });
    }


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        StatusBarUtil.setTranslucentStatus(this, true);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
        //获取地图控件引用
        mMapView = findViewById(R.id.map);
        mSlideLayout = findViewById(R.id.slide_layout);
        mSvInfo = findViewById(R.id.sv_info);
        mTvMore = findViewById(R.id.tv_more);
        mTvMore.setOnClickListener(this);
        mSlideLayout.setInterceptChecker(this);
        mMapView.onCreate(savedInstanceState);

        mapNavigation = new MapNavigation(mContext);
        mapNavigation.initView(mMapView);
        LogUtils.d(MyUtils.getScreenHeight(mContext) + "px");
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initData() {
        findViewById(R.id.fl_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtils.d("???????");
            }
        });

        mSvInfo.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (mSvInfo.getScrollY() == 0) {
                    //顶部
                    shouldIntercept = true;
                } else {
                    shouldIntercept = false;
                }

            }
        });
        mSlideLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                float alpha = (1000 - mSlideLayout.getY()) / 1000;
                mRlTitle.setAlpha(alpha);
                mView2.setAlpha(alpha);
                return false;
            }
        });
        showAdapter = new PictureShowAdapter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        loadingPopupShow();
        networkRequest(netApi.getOrderDetails(deliver_sn), this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    boolean shouldIntercept = true;

    @Override
    public boolean checkIfIntercept() {
        return shouldIntercept;
    }

    @SuppressLint({"NonConstantResourceId", "MissingInflatedId"})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_Logistics_track:
                logisticsTrack();
                break;
            case R.id.tv_more:
                BubblePopupWindow leftTopWindow = new BubblePopupWindow(this);
                View bubbleView = LayoutInflater.from(this).inflate(R.layout.dialog_attach_more, null);
                leftTopWindow.setBubbleView(bubbleView); // 设置气泡内容
                bubbleView.findViewById(R.id.tv_confirm_cancellation).setOnClickListener(this);
                leftTopWindow.show(mTvMore, Gravity.TOP, 0); // 显示弹窗
                break;
            case R.id.btn_confirm_receipt:
            case R.id.btn_confirm_departure:
            case R.id.btn_confirm_sign_for:
            case R.id.btn_receipt_pending:
                changeStatus();
                break;
            case R.id.btn_incremental_expenses:
                startActivity(new Intent(mActivity, IncrementalExpensesActivity.class)
                        .putExtra("deliver_sn", data.getOrder_info().getDeliver_sn()));
                break;
            case R.id.btn_cash_register:
                cashRegister();
                break;
            case R.id.tv_waybill_number:
            case R.id.tv_copy2:
                orderDetailsReuse.mClipData = ClipData.newPlainText("订单号", deliver_sn);
                orderDetailsReuse.mClipboardManager.setPrimaryClip(orderDetailsReuse.mClipData);
                ToastUtil.show("复制成功");
                break;
            case R.id.btn_waybill:
                startActivity(new Intent(mActivity, WaybillDetailsActivity.class)
                        .putExtra("waybill_sn", data.getWaybill_info().getWaybill_sn()));
                break;
            case R.id.btn_confirm_cancellation:
            case R.id.tv_confirm_cancellation:
                confirmCancel();
                break;
            case R.id.tv_service:
                startActivity(new Intent(mActivity, CustomerServiceActivity.class));
                break;
        }
    }

    private LogisticsTrackDialog trackDialog;

    private void logisticsTrack() {
        if (trackDialog == null) {
            trackDialog = new LogisticsTrackDialog(this, deliver_sn);
            trackDialog.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    orderDetailsReuse.mClipData = ClipData.newPlainText("订单号", deliver_sn);
                    orderDetailsReuse.mClipboardManager.setPrimaryClip(orderDetailsReuse.mClipData);
                    ToastUtil.show("复制成功");
                }
            });
        }
        trackDialog.show();
    }

    private void confirmCancel() {
        new XPopup.Builder(mActivity)
                .asConfirm("提示", "取消确认",
                        "取消", "确定",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                networkRequest(netApi.confirm_cancel_apply(data.getOrder_info().getDeliver_sn()), OrderDetailsActivity.this, CONFIRM_RECEIPT);
                            }
                        }, null, false)
                .show();
    }

    private void cashRegister() {
        new XPopup.Builder(this)
                .asConfirm("提示", "确定已经现金收款吗",
                        "取消", "确定",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                if (data.getOrder_info().getPay_method() == 1) {
                                    networkRequest(netApi.confirm_pay_other(deliver_sn, data.getFee_detail().get(data.getFee_detail().size() - 1).getFee_id()), OrderDetailsActivity.this, CONFIRM_COLLECT_MONEY);
                                } else {
                                    networkRequest(netApi.apply_pay_main(deliver_sn), OrderDetailsActivity.this, CONFIRM_COLLECT_MONEY);
                                }
                            }
                        }, null, false)
                .show();
    }

    private final int CONFIRM_RECEIPT = 101;
    private final int CONFIRM_COLLECT_MONEY = 102;

    public void changeStatus() {
        String hint = null;
        SourceGoodsDetailsBean.DataDTO.OrderInfoDTO order_info = data.getOrder_info();
        if (order_info.getStatus() == 5) {
            hint = "您确定揽收吗？";
        } else if (order_info.getStatus() == 7) {
            startActivity(new Intent(this, ShipmentsActivity.class)
                    .putExtra("type", 1)
                    .putExtra("line_id", order_info.getLine_id())
                    .putExtra("deliver_sn", order_info.getDeliver_sn()));
            return;
        } else if (order_info.getStatus() == 11) {
            startActivity(new Intent(this, SignForActivity.class)
                    .putExtra("deliver_sn", order_info.getDeliver_sn())
                    .putExtra("type", 1));
            return;
        } else if (order_info.getStatus() == 13) {
            startActivity(new Intent(this, SignForActivity.class)
                    .putExtra("deliver_sn", order_info.getDeliver_sn())
                    .putExtra("type", 2));
            return;
        }
        new XPopup.Builder(this)
                .asConfirm("提示", hint,
                        "取消", "确定",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                if (order_info.getStatus() == 5) {
                                    networkRequest(netApi.confirmRevenue(order_info.getDeliver_sn()), OrderDetailsActivity.this, CONFIRM_RECEIPT);
                                }

                            }
                        }, null, false)
                .show();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            loadingPopupDismiss();
            SourceGoodsDetailsBean dataBean = new Gson().fromJson(json, SourceGoodsDetailsBean.class);
            if (dataBean.isStatus()) {
                data = dataBean.getData();
                orderDetailsReuse.initData(data);
                setData();
            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        } else {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                loadingPopupShow();
                networkRequest(netApi.getOrderDetails(deliver_sn), this);
            }
        }
    }

    private PictureShowAdapter showAdapter;

    private void setData() {
        SourceGoodsDetailsBean.DataDTO.OrderInfoDTO order_info = data.getOrder_info();
        //mapNavigation.setToLocation(data);
        btnConfirmCancellation.setVisibility(order_info.getCancel_status() == 1 ? View.VISIBLE : View.GONE);
        mBtnConfirmReceipt.setVisibility(order_info.getStatus() == 5 ? View.VISIBLE : View.GONE);
        mBtnConfirmDeparture.setVisibility(order_info.getStatus() == 7 ? View.VISIBLE : View.GONE);
        mBtnWaybill.setVisibility(order_info.getStatus() == 9 && module != 3 ? View.VISIBLE : View.GONE);
        mBtnConfirmSignFor.setVisibility(order_info.getStatus() == 11 ? View.VISIBLE : View.GONE);
        mBtnReceiptPending.setVisibility(order_info.getStatus() == 13 ? View.VISIBLE : View.GONE);
        btnCashRegister.setVisibility(order_info.getPay_status() == 0 && module != 3 && order_info.getStatus() != 99 ? View.VISIBLE : View.GONE);
        mTvHint.setText(MyUtils.getStatusMsg(order_info.getStatus(), order_info.getRefuse_notice(),
                order_info.getJiaohuo_type(), order_info.getPeisong_type()));
        if (order_info.getCancel_status() == 1) {
            mTvHint.setText(String.format("货主申请取消订单(%s)", data.getCancel_info().getCancel_reason()));
        }
        //增加费用按钮
        if (order_info.getStatus() >= 15 || module == 3) {
            mBtnIncrementalExpenses.setVisibility(View.GONE);
        }
        //是否显示更多按钮
        if (order_info.getCancel_status() == 1 && order_info.getPay_status() == 0 && module != 3) {
            mTvMore.setVisibility(View.VISIBLE);
            btnConfirmCancellation.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(data.getWaybill_info().getLicense_plate())) {
            mLlStowage.setVisibility(View.VISIBLE);
            mTvLicensePlateNumber.setText(data.getWaybill_info().getLicense_plate());
            mTvDriver.setText(data.getWaybill_info().getDriver_name());
            mTvDriverPhone.setText(data.getWaybill_info().getDriver_mobile());
            String info = String.format("到站公司：%s\n到站经理：%s\n到站电话：%s\n到站地址：%s",
                    data.getWaybill_info().getOutlets_name(), data.getWaybill_info().getOutlets_county(), data.getWaybill_info().getOutlets_mobile(), data.getWaybill_info().getOutlets_address());
            mTvArrivalInformation.setText(info);
            mTvDepartureTime.setText(DateUtils.stampToDate(data.getWaybill_info().getCreate_time()));
        } else {
            mLlStowage.setVisibility(View.GONE);
        }

        if (!MyUtils.isEmpty(data.getImage_list().getImg_15())) {
            List<Object> urls = new ArrayList<>();
            List<PictureShowBean> pictureShowBeanList = new ArrayList<>();
            for (SourceGoodsDetailsBean.DataDTO.ImageListDTO.ImgDTO imgDTO : data.getImage_list().getImg_15()) {
                pictureShowBeanList.add(new PictureShowBean(imgDTO.getImg_path()));
                urls.add(MyUtils.watermark(imgDTO.getImg_path()));
            }
            for (SourceGoodsDetailsBean.DataDTO.ImageListDTO.ImgDTO imgDTO : data.getImage_list().getImg_16()) {
                pictureShowBeanList.add(new PictureShowBean(imgDTO.getImg_path()));
                urls.add(MyUtils.watermark(imgDTO.getImg_path()));
            }
            //要延时的程序
            mRvSigner.setAdapter(showAdapter);
            mRvSigner.setLayoutManager(new GridLayoutManager(mContext, 3));
            showAdapter.setNewData(pictureShowBeanList);
            mTvSignerTime.setText(DateUtils.stampToDate(data.getImage_list().getImg_15().get(0).getCreate_time()));
            showAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    new XPopup.Builder(mActivity)
                            .asImageViewer(view.findViewById(R.id.iv_picture), position, urls, null, new SmartGlideImageLoader())
                            .isShowSaveButton(false)
                            .show();
                }
            });
        } else {
            mLlSigner.setVisibility(View.GONE);
        }
        if (!MyUtils.isEmpty(data.getImage_list().getImg_13())) {
            mLlReceipt.setVisibility(View.VISIBLE);
            List<Object> urls = new ArrayList<>();
            List<PictureShowBean> pictureShowBeanList = new ArrayList<>();
            for (SourceGoodsDetailsBean.DataDTO.ImageListDTO.ImgDTO imgDTO : data.getImage_list().getImg_13()) {
                pictureShowBeanList.add(new PictureShowBean(imgDTO.getImg_path()));
                urls.add(MyUtils.watermark(imgDTO.getImg_path()));
            }
            PictureShowAdapter showAdapter = new PictureShowAdapter();
            mRvReceipt.setAdapter(showAdapter);
            mRvReceipt.setLayoutManager(new GridLayoutManager(mContext, 3));
            showAdapter.setNewData(pictureShowBeanList);
            mTvReceiptTime.setText(DateUtils.stampToDate(data.getImage_list().getImg_13().get(0).getCreate_time()));
            showAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    new XPopup.Builder(mActivity)
                            .asImageViewer(view.findViewById(R.id.iv_picture), position, urls, null, new SmartGlideImageLoader())
                            .isShowSaveButton(false)
                            .show();
                }
            });
        } else {
            mLlReceipt.setVisibility(View.GONE);
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }
}